﻿<template>
  <el-form ref="planSettingRef" :model="planSettingForm" :rules="formRule" label-width="auto">
    <el-form-item label="租赁模式" prop="rentModelTypeList">
      <el-checkbox-group v-model="planSettingForm.rentModelTypeList" @change="beforeCreateSku">
        <el-checkbox
          v-for="item in getConfig('qingyun.product.rent.model.type')"
          :key="item.dictValue"
          :value="item.dictValue"
        >
          <template #default>
            <div class="check-item">{{ item.dictLabel }}</div>
          </template>
        </el-checkbox>
      </el-checkbox-group>
      <div class="check-item-bottom">
        <div class="bottom-item">
          <div class="bottom-item-content bottom-flex">
            <el-form-item
              label="归还规则"
              label-position="top"
              :prop="planSettingForm.returnRule"
              :rules="formRule.returnRule"
            >
              <el-radio-group v-model="planSettingForm.returnRule" @change="beforeCreateSku">
                <el-radio
                  v-for="item in getConfig('qingyun.product.return.rule')"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  size="large"
                >
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="买断规则"
              label-position="top"
              :prop="planSettingForm.buyOutRule"
              :rules="formRule.buyOutRule"
            >
              <el-radio-group v-model="planSettingForm.buyOutRule" @change="beforeCreateSku">
                <el-radio
                  v-for="item in getConfig('qingyun.product.buy.out.rule')"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  size="large"
                >
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
        <div class="bottom-item">
          <div class="bottom-item-content">
            <el-form-item
              label="买断规则"
              label-position="top"
              :prop="planSettingForm.buyRule"
              :rules="formRule.buyRule"
            >
              <el-radio-group v-model="planSettingForm.buyRule" @change="beforeCreateSku">
                <el-radio
                  v-for="item in getConfig('qingyun.product.buy.out.rule')"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  size="large"
                >
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="商品属性" prop="chooseSpecList" style="position: relative">
      <el-row>
        <el-col :span="24">
          <el-cascader
            ref="attrCascaderRef"
            v-model="planSettingForm.chooseSpecList"
            :options="classAttrData?.length ? classAttrData : operableAttrList"
            :props="selectProps"
            :clearable="true"
            style="width: 500px; margin-bottom: 10px"
            placeholder="请选择商品属性"
            @change="changeAttr"
          />
        </el-col>
        <el-col :span="24">
          <div class="attr-list" v-if="planSettingForm.chooseSpecList.length">
            <el-space direction="vertical" alignment="start" :size="12">
              <div class="attr-list-title">已选择</div>
              <div class="attr-children" v-for="(item, index) in optionalAttrList" :key="item.id">
                <span>{{ item.attributeName }}</span
                >：
                <el-space :size="8" wrap>
                  <el-tag
                    v-for="(tag, tagIdx) in item.subsets"
                    :key="tagIdx"
                    closable
                    size="default"
                    @close="handleDel(index, tagIdx)"
                  >
                    {{ tag.attributeName }}
                  </el-tag>
                </el-space>
              </div>
              <div class="attr-parent">
                <el-space alignment="start" :size="8">
                  <span>
                    <span style="margin-right: 5px">属性组合</span>
                    <el-tooltip effect="dark" placement="top-start">
                      <template #content>
                        如需「合并属性」时，可以通过选择「组合属性」实现，<br />当选择的组合属性数量>=2时，将触发「组合属性」。
                      </template>
                      <base-icon name="iconfont ic-wenhaobangzhu" :size="16" color="var(--ct4)" />
                    </el-tooltip>
                    :
                  </span>
                  <div
                    :class="{
                      'attr-parent-item': true,
                      'attr-parent-item-active': checkParenAttr.includes(attrParentItem.id),
                    }"
                    v-for="(attrParentItem, index) in optionalAttrList"
                    :key="attrParentItem.id"
                    @click="chooseAttr(attrParentItem.id, index)"
                  >
                    {{ attrParentItem.attributeName }}
                  </div>
                </el-space>
              </div>
            </el-space>
          </div>
        </el-col>
      </el-row>

      <el-button class="reset-btn" link @click="resetAttr">
        <base-icon name="iconfont ic-chexiaocaozuo" :size="16" color="var(--ct2)" />
        <span style="margin-left: 4px"> 恢复属性 </span>
      </el-button>
    </el-form-item>
    <el-form-item label="账期类型" prop="periodType">
      <el-radio-group v-model="planSettingForm.periodType">
        <el-radio :value="1">按1个月为1个账期</el-radio>
        <el-radio :value="2">
          <template #default>
            按<el-input-number
              v-model="planSettingForm.periodDays"
              :controls="false"
              :min="0"
              :style="{ margin: '0 5px' }"
            />月为1个账期
          </template>
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="租赁价格" prop="productSkuList">
      <el-table
        v-loading="tableLoading"
        :data="planSettingForm.productSkuList"
        style="width: 100%"
        :header-cell-style="{ 'background-color': 'var(--fl1)' }"
        :span-method="objectSpanMethod"
      >
        <el-table-column label="租赁模式" min-width="200" width="auto" :align="'center'" prop="rentModelType">
          <template #default="scope">{{ rentMode(scope.row.rentModelType) }}</template>
        </el-table-column>
        <el-table-column label="商品规格" min-width="200" width="auto" :align="'center'">
          <template #default="scope">
            <div class="sku-img">
              <info-upload v-model="scope.row.imageUrl" />
              <div class="sku-img-text">{{ skuName(scope.row.allSkus) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" min-width="200" width="auto" :align="'center'">
          <template #default="scope">
            <el-space direction="vertical" alignment="start" :size="12">
              <div>
                官方售价：<el-input-number
                  :min="0"
                  :align="'left'"
                  :controls="false"
                  style="width: 90px"
                  v-model="planSettingForm.productSkuList[scope.$index].officialPrice"
                />
              </div>
              <div>
                商家采购价：<el-input-number
                  :min="0"
                  :align="'left'"
                  :controls="false"
                  style="width: 76px"
                  v-model="planSettingForm.productSkuList[scope.$index].purchasePrice"
                />
              </div>
              <div>
                库存：<el-input-number
                  :min="0"
                  :align="'left'"
                  :controls="false"
                  style="width: 118px"
                  v-model="planSettingForm.productSkuList[scope.$index].quantity"
                />
              </div>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column label="租期" min-width="200" width="auto" :align="'center'">
          <template #default="scope">
            <el-button link @click="openRentDaySet(scope.$index)">
              <el-space :size="5">
                <span>{{ checkDayText(planSettingForm.productSkuList[scope.$index].rentDay) || "点击设置" }}</span>
                <base-icon
                  name="iconfont ic-wenbenbianji"
                  :size="14"
                  :color="'var(--ct2)'"
                  v-if="checkDayText(planSettingForm.productSkuList[scope.$index].rentDay)"
                />
              </el-space>
            </el-button>
          </template>
        </el-table-column>
        <!-- 租期天数列 -->
        <el-table-column
          v-for="dayItem in getConfig('qingyun.product.lease.term')"
          :key="dayItem.dictValue"
          :label="dayItem.dictLabel"
          min-width="200"
          width="auto"
          :align="'center'"
        >
          <template #default="scope">
            <el-space direction="vertical" alignment="start" :size="12">
              <div>
                日均价：
                <el-input-number
                  :min="0"
                  :align="'left'"
                  :controls="false"
                  :disabled="planSettingForm.productSkuList[scope.$index].rentDay[dayItem.dictValue].disabled"
                  style="width: 90px"
                  placeholder="日均价"
                  v-model="planSettingForm.productSkuList[scope.$index].rentDay[dayItem.dictValue].dayPrice"
                />
              </div>

              <div>
                划线价：
                <el-input-number
                  :min="0"
                  :align="'left'"
                  :controls="false"
                  :disabled="planSettingForm.productSkuList[scope.$index].rentDay[dayItem.dictValue].disabled"
                  style="width: 90px"
                  placeholder="划线价"
                  v-model="planSettingForm.productSkuList[scope.$index].rentDay[dayItem.dictValue].underlinePrice"
                />
              </div>

              <div>
                销售价：
                <el-input-number
                  :min="0"
                  :align="'left'"
                  :controls="false"
                  :disabled="planSettingForm.productSkuList[scope.$index].rentDay[dayItem.dictValue].disabled"
                  style="width: 90px"
                  placeholder="销售价"
                  v-model="planSettingForm.productSkuList[scope.$index].rentDay[dayItem.dictValue].salePrice"
                />
              </div>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" width="auto" :align="'center'" fixed="right">
          <template #default="scope">
            <el-space :size="5">
              <el-button link type="primary" @click="handleDelSku(scope.$index)">删除</el-button>
              <el-divider direction="vertical" />
              <el-button link type="primary" @click="handleHideSku(scope.$index)">隐藏</el-button>
            </el-space>
          </template>
        </el-table-column>
        <template #empty>
          <base-empty description="暂无数据" />
        </template>
      </el-table>
    </el-form-item>
    <!-- 物流 -->
    <div class="logistical-title">物流信息</div>
    <el-form-item label="发货邮费" prop="deliveryPostage">
      <el-radio-group v-model="planSettingForm.deliveryPostage">
        <el-radio
          v-for="item in getConfig('qingyun.product.delivery.postage.type')"
          :key="item.dictValue"
          :value="item.dictValue"
        >
          {{ item.dictLabel }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="发货地区" prop="areaList">
      <el-cascader
        placeholder="请选择省市区"
        ref="cascaderRef"
        v-model="planSettingForm.areaList"
        :options="areaData"
        :style="{ width: '430px' }"
        :props="{ label: 'text' }"
      />
    </el-form-item>
    <el-form-item label="归还邮费" prop="returnPostage">
      <el-radio-group v-model="planSettingForm.returnPostage">
        <el-radio
          v-for="item in getConfig('qingyun.product.return.postage.type')"
          :key="item.dictValue"
          :value="item.dictValue"
        >
          {{ item.dictLabel }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="归还地址" prop="returnAddressIdList">
      <el-button class="add-btn" @click="handleOpenModal('add')">添加地址</el-button>
      <el-table
        ref="addressTableRef"
        :data="addressData"
        style="width: 100%; margin-top: 12px"
        show-overflow-tooltip
        :header-cell-style="{ 'background-color': 'var(--fl1)' }"
        row-key="id"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column prop="name" label="收货人" width="auto" align="center" min-width="25%" />
        <el-table-column label="收货地址" width="auto" align="center" min-width="25%">
          <template #default="scope">
            {{ `${scope.row.provinceName}${scope.row.cityName}${scope.row.areaName}${scope.row.street}` }}
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="手机号码" width="auto" align="center" min-width="25%" />
        <el-table-column prop="createTime" label="添加时间" width="auto" align="center" min-width="25%" />
        <template #empty>
          <base-empty description="暂无数据" />
        </template>
      </el-table>
      <div class="page-content">
        <el-pagination
          v-if="total > addressData.length"
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="searchParams.pageSize"
          @current-change="handleCurrentChange"
          v-model:current-page="searchParams.pageNumber"
        />
      </div>
    </el-form-item>
    <!-- 租期选择 -->
    <base-dialog
      v-model="rentDayVisble"
      title="添加租期"
      width="600"
      :show-footer="true"
      destroy-on-close
      @close="handelHide"
      @cancel="handelHide"
      @confirm="handleConfirm"
    >
      <el-checkbox-group v-model="checkDayList">
        <el-checkbox
          v-for="item in getConfig('qingyun.product.lease.term')"
          :key="item.dictValue"
          :label="item.dictLabel"
          :value="item.dictValue"
        />
      </el-checkbox-group>
    </base-dialog>
    <!-- 新增地址 -->
    <address-operate
      :visble="addressVisble"
      :modal-type="operateType"
      :area-data="areaData"
      :current-type="2"
      @hide="handleHideModal"
    />
  </el-form>
</template>

<script setup>
  import InfoUpload from "./InfoUpload.vue";
  import AddressOperate from "../AddressOperate.vue";
  const props = defineProps({
    attributeList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    areaData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    operableAttrList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  });
  // 获取配置选项
  const getConfig = inject("getConfig");
  // 详情
  const detail = inject("detail");
  // 类目数据
  const classAttrList = inject("classAttrList");
  // 属性列表配置参数
  const selectProps = { multiple: true, label: "attributeName", children: "subsets", value: "id", emitPath: false };
  // 当前方案
  const currentPlan = ref(0);
  // 表单Ref
  const planSettingRef = ref();
  // 表单
  const planSettingForm = ref({
    rentModelTypeList: [],
    returnRule: "",
    buyOutRule: "",
    buyRule: "",
    periodType: "",
    periodDays: "",
    chooseSpecList: [],
    productSkuList: [],
    deliveryPostage: "",
    areaList: [],
    returnPostage: "",
    returnAddressIdList: [],
  });
  // 表单规则
  const formRule = reactive({
    rentModelTypeList: [{ required: true, message: "请选择租赁模式", trigger: "change" }],
    returnRule: [{ required: false, message: "请选择归还规则", trigger: "blur" }],
    buyOutRule: [{ required: false, message: "请选择买断规则", trigger: "blur" }],
    buyRule: [{ required: false, message: "请选择买断规则", trigger: "blur" }],
    periodType: [{ required: true, message: "请选择账期类型", trigger: "change" }],
    periodDays: [{ required: false, message: "请选择账期类型", trigger: "change" }],
    chooseSpecList: [{ required: true, message: "请选择属性", trigger: "change" }],
    productSkuList: [{ required: true, message: "请设置租赁价格", trigger: "change" }],
    deliveryPostage: [{ required: true, message: "请选择发货邮费", trigger: "blur" }],
    areaList: [{ required: true, message: "请选择发货地区", trigger: "blur" }],
    returnPostage: [{ required: true, message: "请选择归还邮费", trigger: "blur" }],
    returnAddressIdList: [{ required: true, message: "请选择归还地址", trigger: "blur" }],
  });
  // 属性列表（原数据）
  // const attributeList = ref([]);
  // 可操作的类目属性列表
  const classAttrData = ref([]);
  // 运营自定义的属性列表
  // const operableAttrList = ref([]);
  // 当前可选择的属性列表
  const optionalAttrList = ref([]);
  // 当前可选择未删除的属性列表-用于恢复属性操作
  const originalOptionalAttrList = ref([]);
  // 已选择的父级
  const checkParenAttr = ref([]);
  // 租期天数选择弹窗显示
  const rentDayVisble = ref(false);
  // 当前编辑索引
  const currentIdx = ref(null);
  // 当前选择天数
  const checkDayList = ref([]);
  // sku表格加载
  const tableLoading = ref(false);
  // 属性级联ref
  const attrCascaderRef = ref();
  // 省市区ref
  const cascaderRef = ref();
  // // 省市区数据
  // const areaData = ref([]);
  // 弹窗显示隐藏
  const addressVisble = ref(false);
  // 弹窗类型
  const operateType = ref("");
  // 地址数据
  const addressData = ref([]);
  // 地址搜索参数
  const searchParams = ref({
    pageNumber: 1,
    pageSize: 10,
    type: 2,
  });
  // 总数
  const total = ref(0);
  // 表格加载
  const loading = ref(false);
  // 选择列表
  const selectList = ref([]);
  // 地址ref
  const addressTableRef = ref();

  const colFields = ["rentModelType"];
  // 监听
  watch(classAttrList, val => {
    classAttrData.value = val;
  });
  // 租赁模式
  const rentMode = computed(() => {
    return type => {
      const tyeItem = getConfig("qingyun.product.rent.model.type").find(el => el.dictValue === type);
      return tyeItem ? tyeItem.dictLabel : "-";
    };
  });
  // sku规格
  const skuName = computed(() => {
    return skuGroup => {
      const skuList = skuGroup?.map(el => el.attributeName);
      return skuList && skuList.length ? skuList.join(" ") : "-";
    };
  });
  // 选择天数按钮文字
  const checkDayText = computed(() => {
    return dayGroup => {
      const btnText = [];
      for (let key in dayGroup) {
        if (!dayGroup[key].disabled) {
          const dayStr = `${key}天`;
          btnText.push(dayStr);
        }
      }
      return btnText.length ? btnText.join("、") : "";
    };
  });
  // 初始化
  onMounted(() => {
    loadAddressData(true);
  });
  const init = (data = null) => {
    // 统一方案
    if (!data && detail.value?.productRentPlanList?.length === 1) {
      const planDetail = detail.value?.productRentPlanList[0];
      // 已选择的属性列表
      const attrList = [];
      // 级联已选择的属性
      const cascaderList = [];
      planDetail.productSpecAssociation.productAttributeList.forEach(item => {
        const attrItem = {
          attributeName: item.specName,
          id: item.specId,
          subsets: item.childrenList.map(el => {
            const cascaderItem = [item.specId, el.specId];
            cascaderList.push(cascaderItem);
            return { attributeName: el.specName, id: el.specId };
          }),
        };
        attrList.push(attrItem);
      });
      // 设置选择的属性父级
      checkParenAttr.value = planDetail.productSpecAssociation.chooseSpecList.map(el => el.specId);
      // 设置当前可操作已选择的属性
      optionalAttrList.value = [...attrList];
      // 设置SKU列表
      const skuList = planDetail.productSkuList.map(item => {
        const rentDay = {};
        getConfig("qingyun.product.lease.term").forEach(el => {
          rentDay[el.dictValue] = {
            days: el.dictValue,
            dayPrice: "",
            underlinePrice: "",
            salePrice: "",
            disabled: true,
          };
        });
        const skuItem = {
          rentModelType: "",
          imageUrl: [item.imageUrl],
          officialPrice: item.officialPrice,
          purchasePrice: item.purchasePrice,
          quantity: item.quantity,
          hideFlag: item.hideFlag,
          rentDay: JSON.parse(JSON.stringify(rentDay)),
          productSkuSpecList: item.productSkuSpecList.map(el => el.specId),
          allSkus: item.productSkuSpecList.map(el => {
            return { id: el.specId, attributeName: el.specName };
          }),
        };
        item.productRentModelTypeList.forEach(el => {
          skuItem.rentModelType = `${el.rentModelType}`;
          el.productSkuPriceList.forEach(rentDay => {
            if (skuItem.rentDay[`${rentDay.days}`]) {
              skuItem.rentDay[rentDay.days].dayPrice = rentDay.dayPrice;
              skuItem.rentDay[rentDay.days].underlinePrice = rentDay.underlinePrice;
              skuItem.rentDay[rentDay.days].salePrice = rentDay.salePrice;
              skuItem.rentDay[rentDay.days].disabled = false;
            }
          });
        });
        return skuItem;
      });
      // 设置表单内容
      planSettingForm.value = {
        rentModelTypeList: planDetail.rentModelTypeList.map(el => `${el}`),
        returnRule: `${planDetail.returnRule || ""}`,
        buyOutRule: `${planDetail.buyOutRule || ""}`,
        buyRule: `${planDetail.buyRule || ""}`,
        periodType: planDetail.periodType,
        periodDays: planDetail?.periodDays || "",
        chooseSpecList: [...cascaderList],
        productSkuList: setTableRowSpan(skuList, colFields),
        deliveryPostage: `${planDetail.deliveryPostage}`,
        areaList: [planDetail.province, planDetail.city, planDetail.district],
        returnPostage: `${planDetail.returnPostage}`,
        returnAddressIdList: planDetail?.productReturnAddressList || [],
      };
      nextTick(() => {
        addressData.value?.map(item => {
          const existItem = planDetail.productReturnAddressList.find(el => el.address_id === item.id);
          if (existItem) {
            addressTableRef.value.toggleRowSelection(item);
          }
        });
      });
    } else {
      const planDetail = JSON.parse(JSON.stringify(data));
      // 已选择的属性列表
      const attrList = [];
      // 级联已选择的属性
      const cascaderList = [];
      planDetail.productSpecAssociation.productAttributeList.forEach(item => {
        const attrItem = {
          attributeName: item.specName,
          id: item.specId,
          subsets: item.childrenList.map(el => {
            const cascaderItem = [item.specId, el.specId];
            cascaderList.push(cascaderItem);
            return { attributeName: el.specName, id: el.specId };
          }),
        };
        attrList.push(attrItem);
      });
      // 设置选择的属性父级
      checkParenAttr.value = planDetail.productSpecAssociation.chooseSpecList.map(el => el.specId);
      // 设置当前可操作已选择的属性
      optionalAttrList.value = [...attrList];
      // 设置SKU列表
      const skuList = planDetail.productSkuList.map(item => {
        const rentDay = {};
        getConfig("qingyun.product.lease.term").forEach(el => {
          rentDay[el.dictValue] = {
            days: el.dictValue,
            dayPrice: "",
            underlinePrice: "",
            salePrice: "",
            disabled: true,
          };
        });
        const skuItem = {
          rentModelType: "",
          imageUrl: [item.imageUrl],
          officialPrice: item.officialPrice,
          purchasePrice: item.purchasePrice,
          quantity: item.quantity,
          hideFlag: item.hideFlag,
          rentDay: JSON.parse(JSON.stringify(rentDay)),
          productSkuSpecList: item.productSkuSpecList.map(el => el.specId),
          allSkus: item.productSkuSpecList.map(el => {
            return { id: el.specId, attributeName: el.specName };
          }),
        };
        item.productRentModelTypeList.forEach(el => {
          skuItem.rentModelType = `${el.rentModelType}`;
          el.productSkuPriceList.forEach(rentDay => {
            if (skuItem.rentDay[`${rentDay.days}`]) {
              skuItem.rentDay[rentDay.days].dayPrice = rentDay.dayPrice;
              skuItem.rentDay[rentDay.days].underlinePrice = rentDay.underlinePrice;
              skuItem.rentDay[rentDay.days].salePrice = rentDay.salePrice;
              skuItem.rentDay[rentDay.days].disabled = false;
            }
          });
        });
        return skuItem;
      });

      // 设置表单内容
      planSettingForm.value = {
        rentModelTypeList: planDetail.rentModelTypeList.map(el => `${el}`),
        returnRule: `${planDetail.returnRule || ""}`,
        buyOutRule: `${planDetail.buyOutRule || ""}`,
        buyRule: `${planDetail.buyRule || ""}`,
        periodType: planDetail.periodType,
        periodDays: planDetail?.periodDays || "",
        chooseSpecList: [...cascaderList],
        productSkuList: setTableRowSpan(skuList, colFields),
        deliveryPostage: `${planDetail.deliveryPostage}`,
        areaList: [planDetail.province, planDetail.city, planDetail.district],
        returnPostage: `${planDetail.returnPostage}`,
        returnAddressIdList: planDetail?.productReturnAddressList || [],
      };
      nextTick(() => {
        handleInitSelect();
      });
    }
  };
  // 重置方案数据
  const planDataReset = () => {
    planSettingRef.value.resetFields();
    planSettingForm.value = {
      rentModelTypeList: [],
      returnRule: "",
      buyOutRule: "",
      buyRule: "",
      periodType: [],
      periodDays: "",
      chooseSpecList: [],
      productSkuList: [],
      deliveryPostage: "",
      areaList: [],
      returnPostage: "",
      returnAddressIdList: [],
    };
    searchParams.value = {
      pageNumber: 1,
      pageSize: 10,
      type: 2,
    };
    checkParenAttr.value = [];
  };
  // 修改属性
  const changeAttr = () => {
    const attrListLabel = attrCascaderRef.value.getCheckedNodes();
    const list = [];
    // 处理一级属性
    attrListLabel.forEach(item => {
      const parentItem = list.find(el => el.id === item.pathValues[0]);
      if (!parentItem) {
        const listItem = { id: item.pathValues[0], attributeName: item.pathLabels[0], subsets: [] };
        list.push(listItem);
      }
    });
    // 处理二级属性
    attrListLabel.forEach(item => {
      if (item.level === 2) {
        const parentIdx = list.findIndex(el => el.id === item.pathValues[0]);
        if (parentIdx !== -1) {
          const childItem = { id: item.pathValues[1], attributeName: item.pathLabels[1] };
          list[parentIdx].subsets.push(childItem);
        }
      }
    });
    // 可选择属性列表
    optionalAttrList.value = JSON.parse(JSON.stringify(list));
    originalOptionalAttrList.value = JSON.parse(JSON.stringify(list));
  };
  // 选择属性
  const chooseAttr = (id, index) => {
    if (!checkParenAttr.value.includes(id)) {
      checkParenAttr.value.push(id);
    } else {
      checkParenAttr.value = checkParenAttr.value.filter(el => el !== id);
    }
    beforeCreateSku();
  };
  // 删除属性
  const handleDel = (index, tagIdx) => {
    optionalAttrList.value[index].subsets.splice(tagIdx, 1);
    beforeCreateSku();
  };
  // 恢复属性
  const resetAttr = () => {
    optionalAttrList.value = [];
    optionalAttrList.value = JSON.parse(JSON.stringify(originalOptionalAttrList.value));
    beforeCreateSku();
  };
  // 生成SKU表格前处理操作
  const beforeCreateSku = () => {
    if (!planSettingForm.value.rentModelTypeList.length || !planSettingForm.value.chooseSpecList.length) {
      return;
    }
    if (tableLoading.value) {
      $msg.warning("正在生成数据，请稍等...");
      return;
    }
    nextTick(() => {
      tableLoading.value = true;
      generateSkuData();
    });
  };
  // 生成SKU表格
  const generateSkuData = debounce(
    () => {
      if (!planSettingForm.value.rentModelTypeList.length || !planSettingForm.value.chooseSpecList.length) {
        return;
      }
      const attrList = [];
      const rentList = [];
      planSettingForm.value.rentModelTypeList.forEach(item => {
        const rentConfig = getConfig("qingyun.product.rent.model.type").find(el => el.dictValue === item);
        const rentItem = { attributeName: rentConfig?.dictLabel, id: item };
        rentList.push(rentItem);
      });
      optionalAttrList.value.forEach(item => {
        // 根据已选择的父级属性查询当前已选择子属性
        if (checkParenAttr.value.indexOf(item.id) !== -1) {
          attrList.push(item.subsets);
        }
      });
      const skuList = [rentList, ...attrList];
      console.warn(skuList, "skuListskuListskuList");

      const productList = cartesianProduct(skuList);
      // 需要合并的字段名，按照合并登记来排序
      const colFields = ["rentModelType"];
      const productSkuList = setTableRowSpan(productList, colFields);
      // 表格数据，表格字段
      planSettingForm.value.productSkuList = productSkuList;
      tableLoading.value = false;
    },
    1000,
    false
  );
  // 生成sku列表
  const cartesianProduct = skuList => {
    // 拼接SKU
    const skuGroupArr = skuList.reduce(
      (a, b) => a.map(x => b.map(y => x.concat([y]))).reduce((a, b) => a.concat(b), []),
      [[]]
    );
    // 产品列表
    const productList = [];
    // 生成列表数据
    skuGroupArr.forEach(item => {
      const itemSkus = item.filter((el, idx) => idx !== 0);
      const rentDay = {};
      getConfig("qingyun.product.lease.term").forEach(el => {
        rentDay[el.dictValue] = {
          rentModelType: item[0].id,
          days: el.dictValue,
          dayPrice: "",
          underlinePrice: "",
          salePrice: "",
          disabled: true,
        };
      });
      const skuItem = {
        rentModelType: item[0].id,
        imageUrl: [],
        officialPrice: "",
        purchasePrice: "",
        quantity: "",
        productSkuSpecList: itemSkus.map(el => el.id),
        rentDay,
        // productSkuPriceList: getConfig("qingyun.product.lease.term").map(el => {
        //   return { rentModelType: item[0].id, days: el.dictValue, dayPrice: "", underlinePrice: "", salePrice: "" };
        // }),
        hideFlag: 0,
        allSkus: itemSkus,
      };
      productList.push(skuItem);
    });
    return productList;
  };
  // 设置合并的行和列
  const setTableRowSpan = (tableData, colFields) => {
    let lastItem = [];
    // 循环需要合并的列
    colFields.forEach((field, index) => {
      tableData.forEach(item => {
        // 存值，把合并字段存入行，为了合并单元格时检索列是否含有该字段
        item.mergeCell = colFields;
        // 合并的字段出现的次数
        const rowSpan = `rowspan_${field}`;
        // 比较上一次的存值和该轮的合并字段，判断是否合并到上个单元格
        if (colFields.slice(0, index + 1).every(e => lastItem[e] === item[e])) {
          // 如果是，合并行；
          item[rowSpan] = 0; // 该轮合并字段数量存0
          // 上轮合并字段数量+1
          lastItem[rowSpan] += 1;
        } else {
          //初始化进入&& 如果不是，完成一次同类合并，lastItem重新赋值，进入下一次计算
          item[rowSpan] = 1; // 该轮合并字段第一次出现，数量存1
          // 改变比较对象，重新赋值，进行下一次计算
          lastItem = item;
        }
      });
    });
    return tableData;
  };
  // 删除SKU
  const handleDelSku = idx => {
    planSettingForm.value.productSkuList.splice(idx, 1);
  };
  // 打开天数选择弹窗
  const openRentDaySet = idx => {
    currentIdx.value = idx;
    const checkList = [];
    for (let key in planSettingForm.value.productSkuList[currentIdx.value].rentDay) {
      if (!planSettingForm.value.productSkuList[currentIdx.value].rentDay[key].disabled) {
        checkList.push(key);
      }
    }
    checkDayList.value = [...checkList];
    rentDayVisble.value = true;
  };
  // 关闭弹窗
  const handelHide = () => {
    rentDayVisble.value = false;
  };
  // 确认
  const handleConfirm = () => {
    if (!checkDayList.value.length) {
      $msg.warning("请选择租期天数");
      return;
    }
    // 设置价格编辑状态
    for (let key in planSettingForm.value.productSkuList[currentIdx.value].rentDay) {
      if (checkDayList.value.includes(key)) {
        planSettingForm.value.productSkuList[currentIdx.value].rentDay[key].disabled = false;
      } else {
        planSettingForm.value.productSkuList[currentIdx.value].rentDay[key].disabled = true;
        planSettingForm.value.productSkuList[currentIdx.value].rentDay[key].dayPrice = "";
        planSettingForm.value.productSkuList[currentIdx.value].rentDay[key].underlinePrice = "";
        planSettingForm.value.productSkuList[currentIdx.value].rentDay[key].salePrice = "";
      }
    }
    rentDayVisble.value = false;
    nextTick(() => {
      checkDayList.value = [];
      currentIdx.value = null;
    });
  };
  // 防抖函数
  function debounce(func, wait, immediate) {
    let timeout; // 定义一个计时器变量，用于延迟执行函数
    return function (...args) {
      // 返回一个包装后的函数
      const context = this; // 保存函数执行上下文对象
      const later = function () {
        // 定义延迟执行的函数
        timeout = null; // 清空计时器变量
        if (!immediate) func.apply(context, args); // 若非立即执行，则调用待防抖函数
      };
      const callNow = immediate && !timeout; // 是否立即调用函数的条件
      clearTimeout(timeout); // 清空计时器
      timeout = setTimeout(later, wait); // 创建新的计时器，延迟执行函数
      if (callNow) func.apply(context, args); // 如果满足立即调用条件，则立即执行函数
    };
  }
  // 列表合并单元格发方法
  const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (row?.mergeCell.includes(column?.property)) {
      const rowspan = row[`rowspan_${column.property}`];
      if (rowspan) {
        return { rowspan: rowspan, colspan: 1 };
      } else {
        return { rowspan: 0, colspan: 0 };
      }
    }
  };
  /* 物流信息 */
  // 获取地址数据
  const loadAddressData = init => {
    Api.product.getAddressList({ ...searchParams.value }).then(res => {
      addressData.value = res.data.records;
      total.value = res.data.total;
      if (init) {
        handleInitSelect();
      }
    });
  };
  // 翻页
  const handleCurrentChange = page => {
    searchParams.value = { ...searchParams.value, pageNumber: page };
    nextTick(() => {
      loadAddressData();
    });
  };
  // 选择
  const handleSelectionChange = val => {
    selectList.value = val;
    planSettingForm.value.returnAddressIdList = val;
  };
  // 打开弹窗
  const handleOpenModal = (type, info) => {
    operateType.value = type;
    addressVisble.value = true;
  };
  // 关闭弹窗
  const handleHideModal = refresh => {
    operateType.value = "";
    addressVisble.value = false;
    if (refresh) {
      loadAddressData();
    }
  };
  // 初始化勾选地址
  const handleInitSelect = () => {
    if (addressData.value.length && planSettingForm.value.returnAddressIdList.length) {
      addressData.value.forEach(item => {
        const existItem = planSettingForm.value.returnAddressIdList.find(el => el.address_id === item.id);
        if (existItem) {
          nextTick(() => {
            addressTableRef.value.toggleRowSelection(item);
          });
        }
      });
    }
  };
  // 表单验证
  const formVerify = async () => {
    return await planSettingRef.value.validate().catch(err => {
      console.warn(err);
      return false;
    });
  };
  // 获取处理后的表单内容
  const getLogistiParams = () => {
    const areaLabel = cascaderRef.value?.getCheckedNodes()[0]?.pathLabels;
    const params = {
      deliveryPostage: planSettingForm.value.deliveryPostage,
      returnPostage: planSettingForm.value.returnPostage,
      province: planSettingForm.value?.areaList[0],
      city: planSettingForm.value?.areaList[1],
      district: planSettingForm?.value.areaList[2],
      provinceName: areaLabel ? areaLabel[0] : "",
      cityName: areaLabel ? areaLabel[1] : "",
      districtName: areaLabel ? areaLabel[2] : "",
      returnAddressIdList: planSettingForm.value?.returnAddressIdList?.map(el => el.id),
    };
    return params;
  };
  // 获取当前表单所有内容
  const handleGetFormContent = () => {
    return {
      planSettingForm: JSON.parse(JSON.stringify(planSettingForm.value)),
      optionalAttrList: JSON.parse(JSON.stringify(optionalAttrList.value)),
    };
  };
  // 外部可调用的方法
  defineExpose({
    formVerify,
    getLogistiParams,
    planDataReset,
    init,
    handleGetFormContent,
    planSettingForm,
    optionalAttrList,
    checkParenAttr,
  });
</script>

<style lang="scss" scoped>
  .check-item {
    width: 600px;
  }
  .check-item-bottom {
    width: 100%;
    // height: 185px;
    margin-top: 8px;
    display: flex;
    .bottom-item {
      width: 620px;
      margin-right: 30px;

      .bottom-item-content {
        width: 100%;
        border-radius: 8px;
        border: 1px solid var(--cb1);
        padding: 16px;
        display: flex;
      }
      .bottom-flex {
        justify-content: space-around;
      }
    }
  }
  .attr-list {
    min-width: 550px;
    padding: 16px;
    border: 1px solid var(--cb1);
    border-radius: 8px;
    .attr-list-title {
      width: 100%;
      color: var(--ct1);
      font-size: 14px;
      font-weight: bold;
    }
    .attr-children {
      color: var(--ct1);
      font-size: 14px;
    }
    .attr-parent {
      width: 100%;
      color: var(--ct1);
      font-size: 14px;
      .attr-parent-item {
        height: 30px;
        padding: 0 12px;
        font-size: 14px;
        color: var(--ct2);
        background-color: var(--fl1);
        cursor: pointer;
        border-radius: 4px;
      }
      .attr-parent-item-active {
        color: var(--bd);
        background-color: var(--bd9);
      }
    }
  }
  .reset-btn {
    position: absolute;
    right: 0;
    top: 0;
  }
  .sku-img {
    width: 100%;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    .sku-img-text {
      width: 100%;
      text-align: center;
      font-size: 14px;
      color: var(--ct2);
      margin-top: 4px;
    }
  }
  .logistical-title {
    width: 100%;
    color: var(--ct1);
    font-size: 16px;
    margin-bottom: 16px;
    font-weight: bold;
  }
</style>
